package com.myweb;

import com.myapp.entity.Role;
import com.myapp.entity.Uzer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

@WebListener
public class MyWeb implements ServletContextListener {

  @PersistenceUnit
  private EntityManagerFactory emf;
  @Resource
  private UserTransaction utx;
  public static final String KEY_EM_FACTORY = "myweb.emf";
  public static final String KEY_USER = "myweb.user";
  public static final String KEY_ADMIN_USERNAME = "myweb.admin.username";
  public static final String KEY_ADMIN_PASSWORD = "myweb.admin.password";
  public static final String KEY_ADMIN_TIMEZONE = "myweb.admin.timezone";
  private static final String TIMEZONE_ID_PREFIXES = "^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
  private static String realPath;

  public static String getRealPath() {
    return realPath;
  }

  @Override
  public void contextInitialized(ServletContextEvent sce) {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    realPath = sce.getServletContext().getRealPath("/");
    System.out.println("INSERT ADMIN");
    EntityManager em = emf.createEntityManager();
    try {
      utx.begin();
      Uzer admin = new Uzer();
      admin.setId(0L);
      admin.setUsername(sce.getServletContext().getInitParameter(MyWeb.KEY_ADMIN_USERNAME));
      admin.setPassword(sce.getServletContext().getInitParameter(MyWeb.KEY_ADMIN_PASSWORD));
      admin.setTimeZone(sce.getServletContext().getInitParameter(MyWeb.KEY_ADMIN_TIMEZONE));
      admin.addRoles(Role.ADMIN);
      admin.addRoles(Role.PHYSICIAN);
      admin.addRoles(Role.NURSE);
      admin.addRoles(Role.HCA);
      admin.setDeleted(false);
      em.merge(admin);
      utx.commit();
    } catch (RollbackException | HeuristicMixedException | HeuristicRollbackException | SecurityException | IllegalStateException | NotSupportedException | SystemException ex) {
      Logger.getLogger(MyWeb.class.getName()).log(Level.SEVERE, null, ex);
    }
    ArrayList<TimeZone> timeZones = new ArrayList<>();
    final String[] timeZoneIds = TimeZone.getAvailableIDs();
    for (final String id : timeZoneIds) {
      if (id.matches(TIMEZONE_ID_PREFIXES)) {
        timeZones.add(TimeZone.getTimeZone(id));
      }
    }
    Collections.sort(timeZones, new Comparator<TimeZone>() {
      @Override
      public int compare(final TimeZone a, final TimeZone b) {
        return a.getID().compareTo(b.getID());
      }
    });
    sce.getServletContext().setAttribute("timezones", timeZones);
  }

  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    if (emf != null && emf.isOpen()) {
      emf.close();
    }
  }
}
